<!--
* description: 备件仓库仓位维护
* author: wangml
* createdDate: 2021-4-7
-->
<template>
  <!--    仓库仓位-->
  <div class="app-container app-container-table">
    <div class="l">
      <div class="leftTable">
        <div class="title">仓库维护</div>
        <el-table
          ref="singleTableL"
          v-loading="tableLoadingL"
          :data="leftTableData"
          style="width: 98%"
          :height="tableHeight"
          border
          :element-loading-text="loadingTextL"
          element-loading-background="rgba(0, 0, 0, 0.1)"
          :highlight-current-row="true"
          @row-dblclick="LrowClick"
        >
          <el-table-column label="序号" type="index" align="center" />
          <template v-for="(item, idx) in tableCols">
            <el-table-column
              :key="idx"
              align="center"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
            />
          </template>
        </el-table>
        <el-row class="forms">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter(o => o.isMust === true)"
            :ref=" comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey "
            :key="comp.compKey"
            :class="comp.type === 'input' ? 'comInp': '' "
            :com-type="comp.comType"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :show-placeholder="comp.placeholder"
            :parent-fileds="comp.parentFileds"
            :code="comp.comType[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :is-input="comp.type === 'input'"
            :is-mul="comp.isMul"
            :span="comp.span || 24"
            :label-name="comp.labelName"
            :o-fields="comp.oFields"
            :options="comp.options"
            :custom-obj="comp.customObj"
            :lookuptype="comp.lookuptype"
            :data-to-object="comp.dataToObject"
            :date-options-type="comp.dateOptionsType"
            @changeCode="changCode"
          />
          <div class="buttons">
            <template v-for="comp in tableButtons">
              <el-button
                :key="comp.compKey"
                :type="comp.type"
                :class="comp.class"
                @click="comp.clickEvent"
              >{{ comp.text }}</el-button>
            </template>
          </div>
        </el-row>
        <el-row />
      </div>
      <div class="rightTable">

        <div class="title">仓位维护</div>
        <el-table
          ref="multipleTableR"
          v-loading="tableLoadingR"
          :data="rightTableData"
          style="width: 98%"
          highlight-current-row
          :element-loading-text="loadingTextR"
          element-loading-background="rgba(0, 0, 0, 0.1)"
          :height="tableHeight"
          border
          tooltip-effect="dark"
          @header-dragend="columnWidthChange"
          @row-dblclick="RrowClick"
          @selection-change="handleSelectionChange"
        >
          <el-table-column label="序号" type="index" align="center" />
          <el-table-column type="selection" width="30" align="center" />
          <template v-for="(item, idx) in tableColsR">
            <el-table-column
              :key="idx"
              align="center"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
              :type="item.type || ''"
            />
          </template>

        </el-table>
        <el-row class="forms">
          <template v-for="comp in tableComponentsR.filter(o => o.isMust === true)">
            <component
              :is="comp.component"
              :ref=" comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey "
              :key="comp.compKey"
              :class="comp.type === 'input' ? 'comInp': '' "
              :com-type="comp.comType"
              :validrule="comp.validrule"
              :code-field="comp.codeField"
              :text-field="comp.textField"
              :popups-key="comp.compKey"
              :show-placeholder="comp.placeholder"
              :parent-fileds="comp.parentFileds"
              :code="comp.comType[comp.codeField]"
              :disabled="comp.disabled"
              :is-require="comp.isRequire"
              :is-input="comp.type === 'input'"
              :is-mul="comp.isMul"
              :span="comp.span || 24"
              :label-name="comp.labelName"
              :o-fields="comp.oFields"
              :options="comp.options"
              :custom-obj="comp.customObj"
              :lookuptype="comp.lookuptype"
              :data-to-object="comp.dataToObject"
              :date-options-type="comp.dateOptionsType"
              @changeCode="changCode"
            />
          </template>
          <div class="buttons">
            <template v-for="comp in tableButtonsR">
              <el-button
                :key="comp.compKey"
                :type="comp.type"
                :class="comp.class"
                @click="comp.clickEvent"
              >{{ comp.text }}</el-button>
            </template>
          </div>
        </el-row>
        <el-row />
      </div>
    </div>
    <div class="r">
      <!--    名称码-->
      <div class="title">备件地址码</div>
      <el-table
        v-loading="tableLoadingX"
        :data="addressCodeData"
        style="width: 99%"
        :element-loading-text="loadingTextX"
        element-loading-background="rgba(0, 0, 0, 0.1)"
        height="65%"
        @row-dblclick="XrowClick"
        @selection-change="handleSelectionChangeX"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="50"
        />
        <el-table-column
          prop="partNo"
          align="center"
          label="备件号"
        />
        <el-table-column
          prop="addressCode"
          align="center"
          label="备件地址码"
        />
        <el-table-column
          prop="isEnableCn"
          align="center"
          label="状态"
        />
      </el-table>
      <!--      分页-->
      <el-pagination
        layout="prev, pager, next"
        :total="addressCodeTotal"
        :current-page.sync="listQuery.pageIndex"
        @size-change="queryAddressCode($event, 'pageSize')"
        @current-change="queryAddressCode($event, 'pageIndex')"
      />
      <el-form
        :inline="false"
        :model="formInline"
        label-width="75px"
        label-position="left"
        class="demo-form"
      >
        <el-form-item label="备件号：">
          <el-input v-model="formInline.partNo" clearable placeholder="请输入备件号" />
        </el-form-item>
        <el-form-item label="地址码：">
          <el-input v-model="formInline.addressCode" clearable placeholder="请输入地址码" @change="addressChange"/>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="formInline.isEnable" placeholder="请选择">
            <el-option
              v-for="item in [
                { label: '启用', value: '1' },
                { label: '停用', value: '0' },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="buttons">
        <el-button type="primary" icon="iconfont icon-importVINCode" @click="submitCode">保存</el-button>
        <el-button type="warning" icon="iconfont icon-deleteSheet" @click="delAddr">删除</el-button>
        <el-button icon="iconfont  icon-reset" @click="resetAddress">重置</el-button>
      </div>
    </div>
    <!-- <import-store-pos
      :popups-visible.sync="switchDia"
    /> -->
  </div>

</template>
<script>
import {
  getStoreData, getPosDataByStore, delStorePos, SaveStoreData
} from '@/views/pa/branchWarehouseManagement/WarehouseSpaceMaintenance/fetchData'
import importStorePos from '@/views/pa/branchWarehouseManagement/WarehouseSpaceMaintenance/importStorePos'
import api from './api'
export default {
  name: 'WarehousePositionMaintenance',
  components: {
    importStorePos
  },
  data() {
    return {
      addrSelections: [],
      curAddressRow: null,
      addressStatus: 'add',
      listQuery: {
        pageIndex: 1,
        pageSize: 20
      },
      addressCodeTotal: 0,
      loadingTextX: '正在加载地址码...',
      tableLoadingX: false,
      formInline: {
        partNo: '',
        addressCode: '',
        isEnable: ''
      },
      addressCodeData: [],
      tableHeight: '45%',
      // switchDia: false,
      tableLoadingL: false,
      loadingTextL: '正在加载仓库信息...',
      tableLoadingR: false,
      loadingTextR: '正在加载仓位信息...',
      // =====================================
      // 左表格数据
      tableCols: [
        { prop: 'warehouseCode', label: '仓库编码', width: '', isRequire: true },
        { prop: 'warehouseName', label: '仓库名称', width: '', isRequire: true },
        { prop: 'isEnableCn', label: '状态', width: '', isRequire: true },
        { prop: 'hasPlace', label: '有仓位', width: '', isRequire: true },
        { prop: 'remark', label: '备注', width: '' }
      ],
      tableButtons: [
        { compKey: 'btn1', type: 'primary', class: 'iconfont  icon-preservation',
          clickEvent: () => {
            for (const atrr in this.leftFormFields) {
              // if (!this.leftFormFields[atrr].trim()) return this.$message('所有输入栏都为必填项！')
            }
            const loading = this.$loading({
              text: '正在加载数据......'
            })
            if (this.curIndex === null) {
              // 新增
              SaveStoreData.call(this, loading)
            } else {
              // 修改
              SaveStoreData.call(this, loading)
            }
          },
          text: '保存'
        },
        { compKey: 'btn2', type: '', class: 'iconfont icon-reset',
          clickEvent: () => {
            !this.leftRef.length ? this.getRef() : ''
            for (const attr in this.leftFormFields) this.leftFormFields[attr] = ''
            this.clearForm()
          },
          text: '重置'
        }
      ],
      tableComponents: [
        { comType: 'leftFormFields', compKey: 'warehouseCode', labelName: '仓库编码：',
          codeField: 'warehouseCode',
          component: () => import('@/components/org/commonInput'),
          type: 'input',
          isMust: true,
          // isRequire: true,
          disabled: false,
          span: 12
        },
        { comType: 'leftFormFields', compKey: 'warehouseName', labelName: '仓库名称：',
          codeField: 'warehouseName',
          component: () => import('@/components/org/commonInput'),
          type: 'input',
          isMust: true,
          disabled: false,
          // validrule: validrule,
          span: 12
        },
        { comType: 'leftFormFields', compKey: 'isEnable', labelName: '状态：',
          codeField: 'isEnable',
          textField: 'isEnableCn',
          oFields: 'value,label',
          // parentFileds: 'value:cityId-deliveryCityName',
          // customObj: {
          //   api: { APIUrl: tdApi.QueryCenterByList.APIUrl },
          //   listQuery: { cityId: '' }
          // },
          options: [
            { value: '1', label: '启用' },
            { value: '0', label: '停用' }
          ],
          component: () => import('@/components/org/commonSelect'),
          isMust: true,
          span: 12
        },
        { comType: 'leftFormFields', compKey: 'remark', labelName: '备注：',
          codeField: 'remark',
          component: () => import('@/components/org/commonInput'),
          type: 'input',
          isMust: true,
          // validrule: validrule,
          span: 12

        }
      ],
      leftFormFields: {
        warehouseCode: '',
        warehouseName: '',
        isEnable: '',
        isEnableCn: '',
        remark: ''
      },
      leftTableData: [],
      leftCurRow: {},
      // =====================================
      // 右表格数据
      curIndexR: null,
      rightCurRow: {},
      tableColsR: [
        // { prop: '', label: '展开', width: '50', type: 'expand' },
        { prop: 'placeCode', label: '仓位编码', width: '120' },
        { prop: 'hasPart', label: '是否有地址码', width: '80' },
        { prop: 'remark', label: '备注', width: '' }
      ],
      tableButtonsR: [
        // { compKey: 'rbtn1', type: '', class: 'iconfont icon-importVINCode',
        //   clickEvent: () => {
        //     this.switchDia = true
        //   },
        //   text: '导入'
        // },
        { compKey: 'rbtn2', type: 'primary', class: 'iconfont  icon-preservation',
          clickEvent: () => {
            // if (this.curIndex === null) {
            //   return this.$message('选择一条上表数据才能保存！')
            // }
            // for (const attr in this.leftFormFields) {
            // if (!this.leftFormFields[attr].trim()) return this.$message('所有输入栏都为必填项！')
            // }
            // if (
            //   this.rightTableData.map(row => row['placeCode']).includes(this.rightFormFields.placeCode)
            // ) return this.$message('仓位不可重复！')
            // 修改状态
            const f = { ...this.rightFormFields }
            if (this.curIndexR !== null) {
              f['placeId'] = this.rightCurRow['placeId']
            }
            const loading = this.$loading({ text: `请稍等...` })
            this.$requestAPI({
              apiUrl: api.saveDlrPartWareSpaceUsingPOST.APIUrl,
              variables: f
            }).then(res => {
              if (res.result === '1') {
                this.$message(res.msg || '保存成功!')
                this.curIndexR = null
                this.clearSomeData()
                getPosDataByStore.call(this, this.leftCurRow)
                getStoreData.call(this)
              } else {
                this.$message(res.msg ? res.msg : '')
              }
            }).catch(err => {
              if (err.response.data.msg) {
                this.$message(err.response.data.msg)
              } else {
                this.$message(err.message)
              }
            }).finally(() => {
              loading.close()
            })
          },
          text: '保存'
        },
        { compKey: 'rbtn3', type: 'warning', class: 'iconfont icon-deleteSheet',
          clickEvent: () => {
            if (!this.selectData.length) return this.$message('请先勾选要删除的数据！')
            this.$confirm('仓位下的地址码将被清空，确定要删除吗？')
              .then(_ => {
                // 请求删除
                delStorePos.call(this)
              }).catch(_ => { })
          },
          text: '删除'
        },
        { compKey: 'rbtn4', type: '', class: 'iconfont icon-reset',
          clickEvent: () => {
            this.rightRef.forEach((comp, index) => {
              if (index) { comp.modelCode = '' }
            })
            for (const attr in this.rightFormFields) {
              if (!(attr === 'warehouseName' || attr === 'warehouseId')) this.rightFormFields[attr] = ''
            }
            this.curIndexR = null
            // this.rightCurRow = {}
          },
          text: '重置'
        }
      ],
      tableComponentsR: [
        { comType: 'rightFormFields', compKey: 'warehouseNameR', labelName: '仓库名称：',
          codeField: 'warehouseName',
          component: () => import('@/components/org/commonInput'),
          type: 'input',
          isMust: true,
          disabled: true,
          // isRequire: true,
          span: 12
        },
        { comType: 'rightFormFields', compKey: 'placeCodeR', labelName: '仓位编码：',
          codeField: 'placeCode',
          component: () => import('@/components/org/commonInput'),
          type: 'input',
          isMust: true,
          // validrule: validrule,
          span: 12
        },
        { comType: 'rightFormFields', compKey: 'remarkR', labelName: '备注：',
          codeField: 'remark',
          component: () => import('@/components/org/commonInput'),
          type: 'input',
          isMust: true,
          // validrule: validrule,
          span: 24
        }
      ],
      rightFormFields: { warehouseName: '',
        placeCode: '', remark: '',
        warehouseId: '' },
      rightTableData: [],
      // 右表选择数据
      selectData: [],
      // 当前编辑行的索引
      curIndex: null,
      leftRef: [],
      rightRef: [],
      tableRef: ['singleTableL', 'multipleTableR']
    }
  },
  watch: {
    'curIndex': function(val) {
      const data = this.tableComponents.filter(o => o.compKey === 'warehouseName' || o.compKey === 'warehouseCode')
      data.forEach(item => {
        item.disabled = val !== null
      })
    }
  },
  mounted() {
    // 请求仓库数据
    this.tableLoadingL = true
    getStoreData.call(this)
  },
  methods: {
    // 校验地址码长度为6-9
    addressChange(){
      let num=this.formInline.addressCode
      if(String(num).trim().length<6 || String(num).trim().length>9){
        this.formInline.addressCode=""
        this.$message('地址码长度为6-9位')
      }
    },
    handleSelectionChangeX(selection) {
      this.addrSelections = selection
    },
    // 地址码删除
    delAddr() {
      this.$confirm('确认要删除吗？', '提示')
        .then(() => {
          const loading = this.$loading({ text: `正在删除...` })
          if (!this.rightCurRow.placeCode) return this.$message('请先双击选择仓位!')
          this.$requestAPI({
            apiUrl: '/mp/e3sh/spareparts/nodestorehouse/dlrPartWarehouseMaintainService/deleteDlrAddressCode.do',
            variables: this.addrSelections
          }).then(res => {
            if (res.result !== '1') return this.$message(res.msg || '删除失败!')
            this.$message(res.msg || '删除成功！')
            this.addrSelections = []
            this.queryAddressCode()
          }).catch(err => {

          }).finally(() => {
            loading.close()
          })
        }).catch(reason => {})
    },
    fillXForm(row) {
      this.$set(this.formInline, 'addressCode', row['addressCode'])
      this.$set(this.formInline, 'partNo', row['partNo'])
      this.$set(this.formInline, 'isEnable', row['isEnable'])
    },
    XrowClick(row) {
      this.addressStatus = 'edit'
      this.curAddressRow = row
      this.fillXForm(row)
    },
    // 重置名称码表单
    resetAddress() {
      this.formInline = {}
      this.addressStatus = 'add'
      this.curAddressRow = null
    },
    submitCode() {
      const loading = this.$loading({ text: `正在保存...` })
      if (!this.rightCurRow.placeCode) return this.$message('请先双击选择仓位!')
      const variables = {
        placeCode: this.rightCurRow.placeCode,
        placeId: this.rightCurRow.placeId,
        ...this.formInline
      }
      if (this.addressStatus === 'edit') {
        variables['addressCodeId'] = this.curAddressRow['addressCodeId']
      }
      this.$requestAPI({
        apiUrl: '/mp/e3sh/spareparts/nodestorehouse/dlrPartWarehouseMaintainService/saveDlrAddressCode.do',
        variables
      }).then(res => {
        if (res.result !== '1') return this.$message(res.msg || '保存失败!')
        this.$message(res.msg || '保存成功！')
        this.formInline = {}
        this.queryAddressCode()
      }).catch(err => {

      }).finally(() => {
        loading.close()
      })
    },
    getRef() {
      const leftRef = []
      const rightRef = []
      for (const item in this.$refs) {
        // 过滤 table ref
        if (!this.tableRef.includes(item)) {
          !item.includes('R')
            ? leftRef.push(this.$refs[item][0])
            : rightRef.push(this.$refs[item][0])
        }
      }
      this.leftRef = leftRef
      this.rightRef = rightRef
    },
    changCode(code, text, codeField, comType, popupsKey, textField) {
      this[comType][codeField] = code
      if (textField) {
        this[comType][textField] = text
      }
    },
    // 表格选择触发
    handleSelectionChange(val) { this.selectData = val },
    // 网格点击事件
    rowClick(row) {
      if (row['index'] === this.curIndex) {
        console.log('aaa')
      }
    },
    // 网格单击事件
    LrowClick(row) {
      this.leftCurRow = row
      this.curIndex = row['index']
      this.tableLoadingR = true
      // 清空 右侧选择行
      // this.clearSomeData()
      this.fillForm(row)
      getPosDataByStore.call(this, row)
    },
    resetAddrData() {
      this.addressCodeData = []
      this.listQuery = { pageSize: 20, pageIndex: 1 }
      this.formInline = {}
      this.addressStatus = 'add'
      this.curAddressRow = null
    },
    clearSomeData() {
      this.rightCurRow = {}
      this.rightFormFields.placeCode = ''
      this.rightFormFields.remark = ''
      // 清库位 和 备注
      this.$refs['placeCodeR'][0].modelCode = ''
      this.$refs['remarkR'][0].modelCode = ''
    },
    queryAddressCode(val, type) {
      this.tableLoadingX = true
      if (val && type) { this.listQuery[type] = val }
      this.$requestAPI({
        apiUrl: '/mp/e3sh/spareparts/nodestorehouse/dlrPartWarehouseMaintainService/queryDlrAddressCodeInfo.do',
        variables: {
          placeId: this.rightCurRow.placeId,
          ...this.listQuery
        }
      }).then(res => {
        if (res.result === '1') {
          this.addressCodeData = res.rows
          this.addressCodeTotal = res.records
        } else {
          this.$message(res.msg || '名称码查询失败!')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      }).finally(() => {
        this.tableLoadingX = false
      })
    },
    RrowClick(row) {
      this.rightCurRow = row
      this.curIndexR = row.index
      this.fillLeftForm(row)
      // 查询名称码
      this.queryAddressCode()
    },
    fillLeftForm(row) {
      this.rightRef.forEach(comp => {
        if (comp.codeField !== 'warehouseName') {
          comp.modelCode = row[comp.codeField]
        }
      })
      for (const attr in this.rightFormFields) {
        if (!(attr === 'warehouseName')) this.rightFormFields[attr] = row[attr]
      }
    },
    // 赋值form
    fillForm(row) {
      !this.leftRef.length ? this.getRef() : ''
      this.leftRef.forEach(comp => {
        comp.modelCode = row[comp.codeField]
      })
      for (const attr in this.leftFormFields) {
        this.leftFormFields[attr] = row[attr]
      }
      this.setRightStoreName(row['warehouseName'], row['warehouseId'])
    },
    // 设置右表仓库字段
    setRightStoreName(storeName, storeId) {
      this.$refs['warehouseNameR'][0].modelCode = storeName
      this.rightFormFields.warehouseName = storeName
      this.rightFormFields.warehouseId = storeId
    },
    clearForm() {
      this.curIndex = null
      this.curIndexR = null
      // 清除当前选择行
      this.leftCurRow = {}
      // 取消高亮
      this.$refs['singleTableL'].setCurrentRow()
      // 清空左表
      this.rightTableData = []
      this.clearSomeData()
      this.$refs['warehouseNameR'][0].modelCode = ''
      this.leftRef.forEach(comp => {
        comp.modelCode = ''
      })
    },
    columnWidthChange(newWidth, oldWidth, column) {
      // var index = this.tableCols.findIndex(o => o.prop === 'car')
      this.$ConfigCache.CacheConfig.setColsWidthInfo(newWidth, oldWidth, column, this.$route.path)
    }
  }
}
</script>

<style scoped lang="scss">

  .el-table {
    margin: 10px 1%;
  }
  div.buttons{
    padding: 8px;
    float: right;
  }

  /deep/ .comInp {
    margin-bottom: 8px;
    label{
      display: inline-block;
      width: 22% !important;
    }
    .el-input {
      width: 70%;
    }
  }
  /deep/.commonSelect .comwidth {
    margin-bottom: 14px;
    label{
      display: inline-block;
      width: 22% !important;
    }
    .el-select {
      width: 70%;
    }
  }
  .el-row.forms {
    padding: 10px;
  }
  .app-container-table {
    box-sizing: border-box;
    width: 100%;
    height: 96%;
    display: flex;
    flex-direction: row;
    .l {
      width: 60%;
      display: flex;
      flex-direction: column;
      .leftTable {
        height: 50%;
        background: #fff;
        border-right: 1px solid #ccc;
        border-bottom: 1px solid #ccc;
        /*resize: horizontal;*/
        overflow: auto;
      }
      .rightTable {
        height: 50%;
        background: #fff;
        /*flex: 1;*/
        border-right: 1px solid #ccc;
      }
    }
    .r {
      width: 40%;
      background: #fff;
      .el-pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        border-bottom: 1px solid rgba(0, 0, 0, .1);
        margin-bottom: 10px;
      }
      .el-form.demo-form {
        margin-top: 10px;
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        .el-form-item.el-form-item--small {
          width: 50%;
          padding: 0 12px;
          margin-bottom: 3px;
          /deep/ .el-form-item__label {
            font-size: 12px !important;
          }
        }
      }
    }
  }
  .title {
    margin: 10px 5px;
    border-left: 3px solid #00a2d4;
    padding-left: 10px;
    font-size: 16px;
    font-weight: bold;
  }

  /deep/.el-table__row {
    cursor: pointer;
    &.current-row .cell{
      white-space: normal;
      color: #2D64B3;
    }
  }
</style>
